/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package meteothread;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import static meteothread.MainFrame.scaleImage;

/**
 *
 * @author bobby
 */
public class LyonWeather extends Thread{
    MainFrame up;
    MainWeather meteoA;
    
    public LyonWeather(MainFrame _up){
        this.up=_up;
    }
    public void run(){
        try {
            JsonElement connexion = up.connectURLAndParse("http://api.openweathermap.org/data/2.5/weather?q=Lyon,fr&lang=fr");
            /*while(!connexion){
               Thread.sleep(250);
            }*/
            Gson myGson = new Gson();
            meteoA = myGson.fromJson(connexion, MainWeather.class);
            updateFields(); 
        } catch (IOException ex) {
            Logger.getLogger(ParisWeather.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(ParisWeather.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void updateFields(){
        try {   
            URL iconUrl = new URL("http://openweathermap.org/img/w/"+meteoA.getWeather().get(0).getIcon()+".png");
            BufferedImage bufferedImage = ImageIO.read(iconUrl);
            BufferedImage newPicture = scaleImage(150,120,bufferedImage);
            up.lyonImage.setIcon(new ImageIcon(newPicture));
            up.txtMeteo2.setText("Situation : "+meteoA.getWeather().get(0).getDescription());
            double tempCelsius1 = (meteoA.getMain().getTemp() - 273.15);
            DecimalFormat df = new DecimalFormat("#.##");
            up.txtTemp2.setText("Temperature : "+df.format(tempCelsius1) + " °C");
        } catch (MalformedURLException ex) {
            Logger.getLogger(LyonWeather.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(LyonWeather.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
